export default function (resources) {
  return {
    data() {
      let initData = {
        remoteDataLoading: 0,
      }
      // 初始化数据, 就可以被Vue添加到响应式属性
      // 存放每个资源的错误信息
      initData.remoteErrors = {}
      for (const key in resources) {
          initData[key] = null
          initData.remoteErrors[key] = null
      }
      return initData
    },
    created() {
      for (const key in resources) {
        let url = resources[key]
        if (typeof url === 'function') {
          this.$watch(url, (val) => {
            this.fetchResource(key, val)
          }, {
            immediate: true,
          })
        } else {
          this.fetchResource(key, url)
        }
      }
    },
    computed: {
      remoteDataBusy() {
        // 大于等于 0 则显示动画
        return this.$data.remoteDataLoading !== 0
      },
      // 检查是否有错误信息
      hadRemoteErrors() {
        // 只要有一项的值不为null，则返回true
        return Object.keys(this.$data.remoteErrors).some(key => this.$data.remoteErrors[key])
      }
    },
    methods: {
      async fetchResource(key, url) {
        // 只要请求，让remoteDataLoading标志加 1，当大于等于1的时候展示loading动画
        this.$data.remoteDataLoading++
        try {
          this.$data[key] = await this.$fetch(url)
        } catch (error) {
          // 存放错误信息
          this.$data.remoteErrors[key] = error
          console.log(error)
        }
        // 请求完成让remoteDataLoading表示器减 1
        this.$data.remoteDataLoading--
      },
    },
  }
}